from collections import OrderedDict
from datetime import datetime
from time import time
import json

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from .serializer import *
from apps import redis_client
from util.auth import OWNTokenAuthentication
from util.page import MyPageNumberPagination
from util.exception import ValidationError
from .models import *


class OrderProductsView(GenericViewSet):
    authentication_classes = [OWNTokenAuthentication]

    @action(detail=False, methods=["GET", ], url_path="orderproduct_list")
    def orderproduct_list(self, requests, *args, **kwargs):
        order_key = requests.GET.get("order_key")
        product_name = requests.GET.get("product_name")
        product_number = requests.GET.get("product_number")
        data = {
            "order_key": order_key if order_key else None,
            "product_name": product_name if product_name else None,
            "product_number": product_number if product_number else None
        }
        serializers = ProductOrderListSerializer(data=data)
        if serializers.is_valid():
            order_key = serializers.validated_data.get("order_key")
            product_name = serializers.validated_data.get("product_name")
            product_number = serializers.validated_data.get("product_number")
            products = ProductOrderModel.objects.filter(order_key=order_key)
            if product_name:
                products = products.filter(product_name__icontains=product_name).all()
            if product_number:
                products = products.filter(product_number__icontains=product_number).all()
            results = []
            for pro in products:
                results.append({
                    "product_name": pro.product_name,
                    "product_number": pro.product_number,
                    "product_sum": pro.product_sum,
                    "key": pro.id,
                })
            page = MyPageNumberPagination()
            page_usrs = page.paginate_queryset(queryset=results, request=requests, view=self)
            return Response(self.__get_paginated_response(page, requests, page_usrs))
        else:
            raise ValidationError(20001)


    def __get_paginated_response(self, page, request, datas):
        a = OrderedDict([
            ('current', int(page.get_page_number(request, page))),
            ('total', int(page.page.paginator.count)),
            ('pageSize', int(page.get_page_size(request))),
            ('data', datas),
            ("code", 200)
        ])
        return a
    @action(detail=False, methods=["GET", ], url_path="temp_list")
    def orderproducttemp_list(self, requests, *args, **kwargs):
        order_key = requests.GET.get("order_key")
        data = {
            "order_key": order_key if order_key else None,
        }
        serializers = ProductOrderListTempSerializer(data=data)
        if serializers.is_valid():
            order_key = serializers.validated_data.get("order_key")
            results = []
            datas = redis_client.hgetall(order_key)
            for key, value in datas.items():
                d = json.loads(value)
                results.append({
                    "key": d.get("key"),
                    "product_number": d.get("product_number"),
                    "product_name": d.get("product_name"),
                    "product_sum": d.get("product_sum")
                })
            return Response({
                "code": 200,
                "result": results,
            })
        else:
            raise ValidationError(20001)

    @action(detail=False, methods=["POST", ], url_path="orderproduct_create")
    def orderproductcreate(self, requests, *args, **kwargs):
        serializer = orderproductCreateSerializer(data=requests.query_params)
        if serializer.is_valid():
            serializer.create(serializer.validated_data)
            return Response({"code": 200, "msg": "添加成功"})
        raise ValidationError(20001)

    @action(detail=False, methods=["POST", ], url_path="createlist")
    def orderproductcreatelist(self, requests, *args, **kwargs):
        t = dict(requests.query_params)
        data = {
            "orderproductids": t if t else {},
        }
        serializer = orderproductCreateListSerializer(data=data)
        if serializer.is_valid():
            key = serializer.create(serializer.validated_data)
            return Response({"code": 200, "msg": "添加成功"})
        raise ValidationError(20001)
